#include "sound_manager.h"

SoundManager* SoundManager::sound;

int SoundManager::Init(HWND hWnd)
{
	sound = this;
	HRESULT hResult = DirectSoundCreate8(NULL, &directSound8, NULL);
	if (hResult != DS_OK) {
		printf("Fail to create directsound object");
		return 1;
	}
	hResult = directSound8->SetCooperativeLevel(hWnd, DSSCL_PRIORITY);
	if (hResult != DS_OK) {
		printf("Direct sound - set cooperative level fail.");
		return 1;
	}
	return 0;
}

LPDIRECTSOUNDBUFFER8 SoundManager::CreateSoundBuffer(mad_pcm *pcm,
    int &bufferSize) {

  /*Variable*/

  DSBUFFERDESC bufferdesc;
  WAVEFORMATEX waveFormat;
  LPDIRECTSOUNDBUFFER buffer = NULL;
  LPDIRECTSOUNDBUFFER8 buffer8;
  /* set up wave format */

  memset(&waveFormat, 0, sizeof(WAVEFORMATEX)); // set value
  waveFormat.cbSize = 0;
  waveFormat.wFormatTag = WAVE_FORMAT_PCM;
  waveFormat.nChannels = pcm->channels;
  waveFormat.nSamplesPerSec = pcm->samplerate;
  waveFormat.nBlockAlign = 4; // bytes per sample per chanel
  waveFormat.nAvgBytesPerSec = waveFormat.nBlockAlign *
    waveFormat.nSamplesPerSec;
  waveFormat.wBitsPerSample = 16;
   
  /* setup buffer descirbe */

  bufferSize = (4 * waveFormat.nAvgBytesPerSec); // 4 sec buffer
  memset(&bufferdesc, 0, sizeof(DSBUFFERDESC));
  bufferdesc.dwSize = sizeof(DSBUFFERDESC);
  bufferdesc.dwReserved = NULL;
  bufferdesc.dwBufferBytes = bufferSize;
  bufferdesc.dwFlags =  DSBCAPS_CTRLPAN | DSBCAPS_CTRLVOLUME | DSBCAPS_CTRLFREQUENCY
  | DSBCAPS_GLOBALFOCUS;
  bufferdesc.lpwfxFormat = &waveFormat;
  bufferdesc.guid3DAlgorithm = DS3DALG_DEFAULT;
  HRESULT hResult = this->directSound8->CreateSoundBuffer(&bufferdesc, &buffer, NULL);
  if (hResult != DS_OK) {
    printf("Create sound buffer fail.");
    return NULL;
  }
  hResult = buffer->QueryInterface(IID_IDirectSoundBuffer8, (LPVOID*)&buffer8);
  buffer->Release();  
  if (hResult != DS_OK) {
	  printf("Create IID_IDirectSoundBuffer8 fail");
    return NULL;
  }
  return buffer8;
}

SoundManager::SoundManager(void)
{

}


SoundManager::~SoundManager(void)
{
	printf("Sound manager: destructor called!");
}
